package com.tmall.testgen.common.socket.syn;

import java.io.OutputStream;

import com.tmall.testgen.client.socket.SocketClient;
import com.tmall.testgen.common.socket.TransferHandler;
import com.tmall.testgen.plugin.ConsoleFactory;

/**
 * @author haojia
 * @date 2014-07-04
 */
public abstract class SynCallBack {

	private Object syn=new Object();
	private Object result;
	
	public boolean callBack(SynObject synObj){
		Object tem=handleReceive(synObj);
		if(tem!=null){
			result=tem;
			synchronized (syn) {
				syn.notifyAll();
			}
			return true;
		}
		return false;
		
	}
	
	public Object sendObj(Object obj,OutputStream out){
		if(obj!=null)
		    writeObect(obj,out);
			//SocketClient.getInstance().writeObect(obj);
		
		SynCallBackCenter.getInstance().addSynCallBack(this);
		
		synchronized (syn) {
			try {
				syn.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
				ConsoleFactory.putError(e);
			}
		}
		
		return result;
		
	}
	protected abstract Object  handleReceive(SynObject synObj);

	public  void writeObect(Object obj,OutputStream out){
        try {
           TransferHandler.writeObject(out, obj);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
	
}
